#include "MessageUnti.hpp"
#include "BaseLog.hpp"
#include "Defind.hpp"

#include <array>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <string>
#include <unistd.h>
#include <utility>
#include <vector>

using namespace DBServer::Base::Unti;


/**-----------------------------------------
 * 
 * client status machine
 * 
 * ------------------------------------------
*/
void ClientStatusMachine::analysis(int fd, char *read_buffer, int max_size, std::vector<std::string>& responds) {
    // define the status
    static const int HEAD_LACK = 0;
    static const int DATA_LACK = 2;

    // read data from fd
    int total_len = read(fd, read_buffer, max_size);

    if (total_len == -1) {
        error("total_len == -1\n");
        exit(1);
    }

    int read_len = 0, status = HEAD_LACK;
    short data_len = 0;
    char data[1024] = {0};

    while (total_len > 0) {
        
        switch (status)
        {
        case HEAD_LACK:
        {
            if (total_len < HEAD_LEN) goto finish;
            memcpy(&data_len, read_buffer+read_len, HEAD_LEN);
            total_len -= HEAD_LEN;
            read_len += HEAD_LEN;
            status = DATA_LACK;
            break;
        }
        case DATA_LACK:
        {
            if (data_len > total_len) goto finish;
            memcpy(data, read_buffer+read_len, data_len);
            total_len -= data_len;
            read_len += data_len;
            status = HEAD_LACK;
            // commit result
            // responds.emplace_back(data, data + data_len);
            
            //std::cout << data << "\n";
            memset(&data_len, 0, sizeof(data_len));
            memset(data, 0, 1024);
            break;
        }
        default:
            break;
        }

    }
finish:
    return;
}